package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhs.storage.bean.ProjectPlan;
import com.hhs.storage.bean.Region;
import com.hhs.storage.bean.ResponseInfo;
import com.hhs.storage.dao.RegionDao;
import com.hhs.storage.service.RegionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.RandomUtils;
import com.hhs.storage.util.SysUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-02-04
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionDao, Region> implements RegionService {

    @Override
    public List<Region> fj() {
        List<Region> list = getByPid("350000");
        SysUtil.FJ_REGION=list;
        return list;
    }

    @Override
    public Map<String, Object> addOrEdit(Region region) {
        if(!StringUtils.isEmpty(region.getPid())){
            Region pRegion = getById(region.getPid());
            //设置合并名称
            region.setMername(pRegion.getMername()+","+region.getName());
            //将层级加1级
            region.setLevel(pRegion.getLevel()+1);
        }
        if(region.getId()==null){
            region.setId(RandomUtils.getRandomString(12));
            this.save(region);
        }else{
            this.updateById(region);
        }
        //更新缓存
        fj();
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> dele(String id) {
        if(StringUtils.isEmpty(id)){
            return ResponseInfo.error("");
        }
        //查询是否有下级
        QueryWrapper<Region> qw=new QueryWrapper<Region>();
        qw.eq("pid",id);
        qw.eq("status",1);
        List<Region> list = this.list(qw);
        if(list!=null && list.size()>0){
            return ResponseInfo.error("该地区有下级，无法删除");
        }
        //将地区设置为弃用
        Region region = this.getById(id);
        region.setStatus(0);
        this.updateById(region);
        //更新缓存
        fj();
        return ResponseInfo.success();
    }

    //递归读取某个地区的所有下级
    private List<Region> getByPid(String pid){
        if(StringUtils.isEmpty(pid)) {
            return null;
        }
        QueryWrapper<Region> qw=new QueryWrapper<Region>();
        qw.eq("pid",pid);
        qw.eq("status",1);
        List<Region> list = this.list(qw);
        for (Region region : list) {
            region.setChildren(getByPid(region.getId()));
        }
        return list;
    }
}
